<?php
namespace app\mxty\model;

use think\Model;
use think\model\concern\SoftDelete;
use app\common\enum\order\PayStatus as OrderPayStatusEnum;

class Booking extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $table = 'athlon_arena_booking';

    // 关联的多个时段信息
    public function fragments()
    {
        return $this->hasMany(BookingFragment::class, 'booking_id');
    }

    // 关联多个裁判
    public function referees()
    {
        return $this->hasMany(BookingReferee::class, 'booking_id');
    }

    // 前台下单预订
    public function order($userId, $date, $total, $fragments, $refereeList)
    {
        return $this->transaction(function () use (
            $userId,
            $date,
            $total,
            $fragments,
            $refereeList
        ) {
            $order = self::create([
                'user_id' => $userId,
                'book' => 1,
                'order_no' => $this->createOrderNo(),
                'start_date' => $date,
                'end_date' => $date,
                'total_price' => $total,
            ]);

            $order->fragments()->saveAll($fragments);

            //  记录订单裁判
            $referees = [];
            foreach ($refereeList as $referee) {
                array_push($referees, [
                    'booking_id' => $order->id,
                    'referee_id' => $referee->referee_id,
                    'referee_name' => $referee->referee_name,
                    'post' => $referee->post,
                    'certificate' => $referee->certificate,
                    'position' => $referee->position,
                    'price' => $referee->price,
                ]);
            }
            $order->referees()->saveAll($referees);
            return $order;
        });
    }

    // 获取用户订场订单
    public static function getListByUserId($userId)
    {
        return self::with(['fragments', 'referees'])
            ->where('user_id', $userId)
       //     ->where('pay_status', OrderPayStatusEnum::SUCCESS)
            ->order('update_time desc')
            ->select();
    }

    // 查询指定日期下已付款的订场单
    public function getBookingByDate($date)
    {
        return $this::with(['fragments', 'referees'])->whereDay('start_date', $date)->where('pay_status', OrderPayStatusEnum::SUCCESS)->select();
    }

    /**
     * 生成订单号
     * @return string
     */
    public function createOrderNo()
    {
        return date('Ymd') .
            substr(
                implode(
                    null,
                    array_map('ord', str_split(substr(uniqid(), 7, 13), 1))
                ),
                0,
                9
            );
    }

    public function getOrderById($id)
    {
        return self::with('fragments')->find($id);
    }

    public function getOrderByNo($order_no)
    {
        return self::with('fragments')
            ->where('order_no', $order_no)
            ->find();
    }
}
